﻿using System;
using System.Buffers;
using System.Text;
using Beefly.Json.Buffer;
using Letter.IO.Buf;

namespace Beefly.Json;

public static class JsonConvert
{
    public static string Serialize<T>(T value)
    {
        var buffer = BufferCache.Current().Get();
        InternalSerialize(buffer, value);
        var seq = buffer.GetReadableBuffer();
        string str = string.Empty;
        foreach (var item in seq)
            str += new string(item.Span);
        BufferCache.Current().Ret(buffer);
        return str;
    }

    public static void Serialize<T>(T value, IBufferWriter<byte> writer)
    {
        Serialize<T>(value, writer, Encoding.UTF8);
    }

    public static void Serialize<T>(T value, IBufferWriter<byte> writer, Encoding encoding)
    {
        if (encoding == null)
            encoding = Encoding.UTF8;
        
        var buffer = BufferCache.Current().Get();
        InternalSerialize(buffer, value);
        var seq = buffer.GetReadableBuffer();
        encoding.GetBytes(seq, writer);
        BufferCache.Current().Ret(buffer);
    }

    public static T Deserialize<T>(string str)
    {
        var buffer = BufferCache.Current().Get();
        var writer = buffer.ToBufferWriter();
        writer.Write(str.AsSpan());
        var value = InternalDeserialize<T>(buffer);
        BufferCache.Current().Ret(buffer);
        return value;
    }

    public static T Deserialize<T>(ref ReadOnlySequence<byte> sequence)
    {
        return Deserialize<T>(ref sequence, Encoding.UTF8);
    }

    public static T Deserialize<T>(ref ReadOnlySequence<byte> sequence, Encoding encoding)
    {
        if (encoding == null)
            encoding = Encoding.UTF8;
        
        var buffer = BufferCache.Current().Get();
        var writer = buffer.ToBufferWriter();
        encoding.GetChars(sequence, writer);
        
        var value = InternalDeserialize<T>(buffer);
        BufferCache.Current().Ret(buffer);
        return value;
    }
    
    private static string InternalSerialize<T>(IBuffer<char> buffer, T value)
    {
        return default;
    }

    private static T InternalDeserialize<T>(IBuffer<char> buffer)
    {
        return default;
    }
}